package com.hzit.service.impl;

import com.hzit.entity.Student;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.StudentService;
import com.hzit.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.IOException;
import java.util.List;

public class StudentServiceImpl implements StudentService {

	//1. 查询所有学生
	@Override
	public List<Student> findAll() throws IOException {
		//1.1 得到SqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
		//1.2 得到SqlSession对象
		try (SqlSession session = sqlSessionFactory.openSession()) {
			//1.3 得到StudentMapper对象
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			//1.4 得到所有学生
			List<Student> all = mapper.findAll();
			//1.5 返回
			return all;
		}
	}
	// 2. 查询单个学生
	@Override
	public Student findById(Integer sid) throws IOException {
		//2.1 得到SqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
		//2.2 开始查询
		try(SqlSession sqlSession = sqlSessionFactory.openSession()){
			StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
			Student student = mapper.findById(sid);
			return student;
		}
	}
	// 3. 添加学生
	@Override
	public void add(Student student) throws IOException {
		//3.1 得到SqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
		//3.2 开始添加学生
		try(SqlSession sqlSession = sqlSessionFactory.openSession(true)){
			StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
			mapper.save(student);
		}
	}

	//4. 修改学生
	@Override
	public void update(Student student) throws IOException {
		//4.1 得到SqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
		//4.2 开始修改
		try(SqlSession sqlSession = sqlSessionFactory.openSession(true)){
			StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
			mapper.update(student);
		}
	}

	//5. 删除学生
	@Override
	public void delete(Integer sid) throws IOException {
		//5.1 得到SqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
		//5.2 根据主键删除学生
		try(SqlSession session = sqlSessionFactory.openSession(true)){
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			mapper.delete(sid);
		}
	}
}
